//
//  WFComposeView.swift
//  WangFangWeiBo
//
//  Created by 王方 on 16/7/16.
//  Copyright © 2016年 wf. All rights reserved.
//

import UIKit
import pop
class WFComposeView: UIView {
    
    // MARK:  - 懒加载
    //引入了桥接文件
    private lazy var bgImageView:UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    //定义控制器,用于接收此view装载的viewcontroller
   private var target:UIViewController?
    //定义数组来保存六个菜单按钮
    private lazy var btnArrays = [WFComposeMenuBtn]()
    
    // MARK:  - 构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:  - 初始化控件
    private func setUpUI(){
        backgroundColor = RandomColor()
        self.frame.size = CGSizeMake(ScreenWidth, ScreenHeight)
        addSubview(bgImageView)
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
            
        }
        //添加六个子控件
        addChildBtn()
    }
    // MARK:  - 添加六个子控件
    private func addChildBtn(){
        let btnW:CGFloat = 80
        let btnH:CGFloat = 110
        let itemMargin:CGFloat = (width - 3 * btnW) / 4
        let composeMenuArr = loadPListCompose()
        
        for (i,value) in composeMenuArr.enumerate() {
            let btn = WFComposeMenuBtn()
            btn.addTarget(self, action: "btnAction:", forControlEvents: .TouchUpInside)
            btn.size = CGSizeMake(btnW, btnH)
            //列索引
            let colIndex = i % 3
            //航索引
            let rowIndex = i / 3
            btn.x = btnW * CGFloat(colIndex) + CGFloat(colIndex + 1) * itemMargin
            
            //一开始的时候是放于最下面的,所以加上一屏的高度
             btn.y = btnH * CGFloat(rowIndex) + CGFloat(rowIndex) * itemMargin + ScreenHeight
            btn.setImage(UIImage(named: value.icon!), forState: .Normal)
            btn.setTitle(value.title!, forState: .Normal)
            addSubview(btn)
            btnArrays.append(btn)
        }
    }
    
    private func loadPListCompose()->[WFComposeMenu]{
    let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        let dicArray = NSArray(contentsOfFile: path)!
        var tempArray = [WFComposeMenu]()
        for dic in dicArray {
            let commenu = WFComposeMenu (dic: dic as! [String:AnyObject])
            tempArray.append(commenu)
        }
        return tempArray
    }
    
    // MARK:  - 开启动画
    private func startPopAnimation(value:WFComposeMenuBtn,i:Int,isUp:Bool){
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        let y = isUp ? value.centerY - 350 : value.centerY + 350
        //动画目的地
        animation.toValue = NSValue(CGPoint: CGPoint(x: value.centerX, y: y))
        animation.springBounciness = 8
        animation.springSpeed = 10
        animation.beginTime = CACurrentMediaTime() + Double(i) * 0.025
        value.pop_addAnimation(animation, forKey: nil)
    }
    
    // MARK:  - 对外提供pop视图的显示
    func show(target:UIViewController){
        self.target = target
//        
//        let window =  UIApplication.sharedApplication().windows.last!
//        
//        window.addSubview(self)
        
        
        //添加在控制器上
            target.view.addSubview(self)
        //开启动画
        for (i,value) in btnArrays.enumerate() {
            startPopAnimation(value, i: i, isUp: true)
        }

    }
    
    // MARK:  - 点击单个按钮执行的方法
    @objc private func btnAction(btn:WFComposeMenuBtn) {
        UIView.animateWithDuration(0.25
            , animations: { () -> Void in
                for value in self.btnArrays {
                    value.alpha = 0.2
                    if value == btn {
                        value.transform = CGAffineTransformMakeScale(2, 2)
                    }else{
                        value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                    }
                    
                }
            }) { (_) -> Void in
                //动画执行完毕后还原了
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    for value in self.btnArrays {
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                    }
                    }, completion: { (_) -> Void in
                      self.showComposeVC()
                })
        }
        
        
    }
    
    // MARK:  - 弹出控制器,移除视图
    private func showComposeVC(){
        let composeVC = WFComposeVC()
        
        let nav = UINavigationController(rootViewController: composeVC)
        //跳转目标控制器
        self.target?.presentViewController(nav, animated: true, completion: { () -> Void in
            //需要移除,不然会报警告,无法弹出
            self.removeFromSuperview()
        })
        
    }
    
    
    // MARK:  - 点击屏幕其他的地方收起按钮
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for (i,value) in btnArrays.reverse().enumerate(){
            startPopAnimation(value, i: i, isUp: false)
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            
            UIView.animateWithDuration(0.5, animations: { () -> Void in
                self.alpha = 0
                }, completion: { (_) -> Void in
                    //  结束刷新

                    self.removeFromSuperview()
            })
            
            
            
            
        })
    }

}
